<template>
  <div>
    <el-container>
      <el-header>
        <div>
          <el-menu class="el-menu-demo" mode="horizontal">
            <el-menu-item index="home">
              <router-link to="/home">主页</router-link>
            </el-menu-item>
            <el-menu-item index="category">
              <router-link to="/category">分类</router-link>
            </el-menu-item>
            <el-menu-item index="addsomething" style="margin-left: 68%;padding: 0 0">
              <el-link :underline="false"  @click="getCategories"><i class="el-icon-plus"></i></el-link>
            </el-menu-item>
            <el-menu-item index="notice">
              <el-link v-if="$store.state.hasNewMessage == 'yes'" :underline="false"  @click="handleNoticeClick">
                <i class="el-icon-message-solid"></i>
              </el-link>
              <el-link v-else :underline="false"  @click="handleNoticeClick">
                <i class="el-icon-bell"></i>
              </el-link>
            </el-menu-item>
            <div class="m-user-info">
              <el-submenu index="5">
                <template slot="title">
                  <el-avatar :src="user.avatar" width="30px" alt="img"/> {{user.username}}
                </template>
                <el-menu-item index="5-1">
                  <span v-show="!loggedIn"><el-link :underline="false" style="display: block" type="success" @click="login">登录</el-link></span>
                  <span v-show="loggedIn"><el-link :underline="false" style="display: block" type="success" @click="handleClickAvatar">个人主页</el-link></span>
                  <span v-show="loggedIn"><el-link :underline="false" style="display: block" type="danger" @click="logout">注销</el-link></span>
                </el-menu-item>
              </el-submenu>
            </div>
          </el-menu>
        </div>
      </el-header>
      <el-main class="m-content">
        <el-dialog title="上传图片" :visible.sync="dialogFormVisible">
          <el-form :model="uploadForm" :rules="rules" ref="uploadForm">
            <el-form-item prop="title" label="主题" :label-width="formLabelWidth">
              <el-input v-model="uploadForm.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="open" label="可见性" :label-width="formLabelWidth">
              <el-select v-model="uploadForm.open" placeholder="请选择是否公开">
                <el-option label="公开" value=true></el-option>
                <el-option label="私密" value=false></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="category" label="类别" :label-width="formLabelWidth">
              <el-select v-model="uploadForm.category" placeholder="请选择类别">
                <el-option v-for="item in categories" :key="item.id" :label="item.memo" :value="item.name"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="选择图片" :label-width="formLabelWidth">
              <el-upload
                class="upload-demo"
                ref="upload"
                action="http://localhost:8083/images/uploads"
                :data="uploadForm"
                :headers="token"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :on-exceed="handleExceed"
                :on-success="handleSuccess"
                :file-list="fileList"
                :auto-upload="false"
                accept="image/png, image/jpeg"
                list-type="text"
                :limit=5>
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过10MB</div>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="imageSubmitUpload">提 交</el-button>
          </div>
        </el-dialog>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import Element from 'element-ui'
import store from '../store'
import axios from 'axios'

export default {
  name: 'Header',
  data () {
    return {
      token: {},
      fileList: [],
      dialogFormVisible: false,
      uploadForm: {
        title: '',
        open: '',
        category: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入主题', trigger: 'blur' }
        ],
        open: [
          { required: true, message: '请选择公开与否', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '请输入分类', trigger: 'blur' }
        ]
      },
      categories: [],
      formLabelWidth: '120px',
      user: {
        username: '未登录',
        avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
      }
    }
  },
  computed: {
    loggedIn () {
      if (this.$store.state.jwt && this.$store.state.userInfo) {
        this.$store.commit('SET_LOGGEDIN_TRUE')
      }
      return this.$store.state.loggedIn
    }
  },
  methods: {
    // 登录
    login () {
      const _this = this
      _this.$router.push('/login')
    },
    // 注销
    logout () {
      const _this = this
      // 首先调用后端logout接口(因该接口需要认证权限,所以需要传入token)
      // 其次调用$store清除用户信息及token
      _this.$axios.get('/logout', {
        headers: {
          Authorization: this.$store.state.jwt
        }
      }).then(res => {
        _this.$store.commit('REMOVE_INFO')
        _this.$router.push('/login')
      })
    },
    getCategories () {
      if (!this.loggedIn) {
        this.handleUnlogined()
        return false
      }
      // console.log('getCategories invoked!')
      this.dialogFormVisible = true
      this.token = this.setToken()
      this.$axios.get('/categories').then(response => {
        this.categories = response.data.data
      })
    },
    handleUnlogined () {
      this.$confirm('登录后才能操作，去登陆?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.push('/login')
      }).catch(() => {
      })
    },
    imageSubmitUpload () {
      this.$refs.uploadForm.validate((valid) => {
        if (valid) {
          // console.log('success submit!')
          this.$refs.upload.submit()
        } else { // 前端验证失败
          // console.log('前端验证失败')
          return false
        }
      })
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    handleExceed (file) {
      this.$notify.error({
        title: '错误',
        message: '最多选择5张图片'
      })
    },
    handleSuccess (response, file, fileList) {
      console.log('handleSuccess:' + response)
      this.$refs.upload.clearFiles() // 清空已上传的文件列表
      this.uploadForm.category = ''
      this.uploadForm.open = ''
      this.uploadForm.title = ''
      this.dialogFormVisible = false
    },
    setToken () {
      return { Authorization: this.$store.getters.getJWT }
    },
    handleClickAvatar () {
      this.$router.push('/profile')
    },
    handleNoticeClick () {
      this.$router.push('/notification')
    },
    sse () {
      const userInfo = this.$store.state.userInfo
      if (userInfo) { // 用户已登录
        // console.log('wow')
        var source = null
        const userId = userInfo.id

        if (window.EventSource) {
          // 建立连接
          source = new EventSource('http://localhost:8083/notification/sse/connect/' + userId)

          /**
           * 连接一旦建立，就会触发open事件
           * 另一种写法：source.onopen = function (event) {}
           */
          source.addEventListener('open', function (e) {
            console.log('建立连接...')
          }, false)

          /**
           * 客户端收到服务器发来的数据
           * 另一种写法：source.onmessage = function (event) {}
           */
          source.addEventListener('message', function (event) {
            // console.log(event.data)
            const notification = JSON.parse(event.data)
            let title = '消息'
            // eslint-disable-next-line eqeqeq
            if (notification.type === 'system') {
              title = '公告'
            }
            Element.Notification.success({
              title: title,
              message: notification.content
            })
            store.commit('set_new_message', 'yes')
          })

          /**
           * 如果发生通信错误（比如连接中断），就会触发error事件
           * 或者：
           * 另一种写法：source.onerror = function (event) {}
           */
          source.addEventListener('error', function (e) {
            if (e.readyState === EventSource.CLOSED) {
              console.log('连接关闭')
            } else {
              console.log('error:' + e)
            }
          }, false)
        } else {
          Element.Notification.error({
            title: '消息',
            message: '当前浏览器不支持Sse'
          })
        }

        // 监听窗口关闭事件，主动去关闭sse连接，如果服务端设置永不过期，浏览器关闭后手动清理服务端数据
        window.onbeforeunload = function () {
          source.close()
          axios.get('/notification/sse/close/' + userId, {
            headers: { Authorization: this.$store.state.jwt }
          })
          console.log('close')
        }
      }
    }
  },
  // 页面创建时即会调用,进而获取用户信息
  created () {
    if (this.$store.getters.getUserInfo) { // 如果username不为空
      this.user.username = this.$store.getters.getUserInfo.nickname
      this.user.avatar = this.$store.getters.getUserInfo.avatar
    }
  },
  mounted () {
    this.sse()
  }
}
</script>

<style scoped>
  /*定义header样式宽度并居中*/
  .m-content {
    margin-top: 20px;
    text-align: center;
  }
  /*导航栏样式*/
  .el-menu-demo{
    margin-top: 0px;
  }
  /*导航栏中用户信息样式*/
  .m-user-info{
    float: right;
  }
  /*清除router-link标签生成的下划线等样式*/
  a {
    text-decoration: none;
  }
  .router-link-active {
    text-decoration: none;
  }
</style>
